package com.homework.note.Util;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
//import com.mongodb.client.gridfs.model.GridFSFile;
//import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * @author htyu
 * @date 2019/4/28
 */
@Service
public class PhotoUtil {

    @Autowired
    MongoDbFactory mongoDbFactory;

    @Autowired
    GridFsOperations fs;

    @Autowired
    GridFSBucket gridFSBucket;

    @Bean
    public GridFSBucket getGridFSBuckets() {
        MongoDatabase db = mongoDbFactory.getDb();
        return GridFSBuckets.create(db);
    }



    /**
     * 插入文件
     * @param file
     * @return
     */
    public GridFSInputFile save(MultipartFile file){

        GridFS gridFS = new GridFS((DB) mongoDbFactory.getDb());
        try{
            InputStream in = file.getInputStream();
            String name = file.getOriginalFilename();
            GridFSInputFile gridFSInputFile = gridFS.createFile(in);
            gridFSInputFile.setFilename(name);
            gridFSInputFile.setContentType(file.getContentType());
            gridFSInputFile.save();
            return gridFSInputFile;
        }
        catch (Exception e){}

        return null;

    }

    /**
     * 据id返回文件
     */
    public GridFSDBFile getById(ObjectId id){

        GridFS gridFS = new GridFS((DB) mongoDbFactory.getDb());

        return gridFS.findOne(new BasicDBObject("_id", id));

    }

    public ObjectId upFile(MultipartFile file) throws IOException {
        ObjectId reDBObj = fs.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
        return reDBObj;
    }

    public ResponseEntity<Resource> getFileStream(String resourceId) throws IOException {
        //GridFSFile mongoFile = fs.findOne(new Query(where("_id").is(resourceId)));
        GridFSFile fsFile = fs.findOne(new Query(where("_id").is(resourceId)));
        GridFsResource mongoFile = convertGridFSFile2Resource(fsFile);
        String filename = "inline; filename=" + URLEncoder.encode(mongoFile.getFilename(), "UTF-8");
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, mongoFile.getContentType())
                .header(HttpHeaders.CONTENT_ENCODING, "UTF-8").header(HttpHeaders.CONTENT_DISPOSITION, filename)
                .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS))
                .body(new InputStreamResource(mongoFile.getInputStream()));
    }


    public GridFsResource convertGridFSFile2Resource(GridFSFile gridFsFile) {
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFsFile.getObjectId());
        return new GridFsResource(gridFsFile, gridFSDownloadStream);
    }



}
